package com.xiaoyu.client.ui.activity.nearby;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.nearby.NearbyShopBean;
import com.xiaoyu.client.model.nearby.ShopParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.home.NearbyShopsActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.utils.LongitudeAndLatitude;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 附近商店搜索页
 * Created by jk 2018/11/12
 */
public class NearbySearchActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.activity_nearby_search_title_back_btn)
    ImageView backBtn;//返回
    @BindView(R.id.activity_nearby_search_title_search_edit)
    EditText mSearchEdit;//搜索内容编辑框
    @BindView(R.id.activity_nearby_search_title_search_btn)
    TextView mSearchBtn;//搜索按钮
    @BindView(R.id.common_recycler_view_empty_page)
    ImageView nodataImg;//没有数据提示图片
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mRefreshLayout;

    private AllPowerfulAdapter mShopAdapter;
    private List<ShopParam> mShopList = new ArrayList<>();//店铺数据列表
    private Context mContext;
    private int page = 1;//当前页数
    private int totalPage;//总页数
    private String lat;//纬度
    private String lng;//经度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nearby_search);
        mContext = this;
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        mShopList.clear();
        lat = String.valueOf(LongitudeAndLatitude.getLngAndLat(this).getLatitude());
        lng = String.valueOf(LongitudeAndLatitude.getLngAndLat(this).getLongitude());
    }

    private void initView() {
        //店铺列表
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        setShopAdapter(mShopList);

        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);


        mSearchEdit.addTextChangedListener(onTextWatcher);
        backBtn.setOnClickListener(this);
        mSearchBtn.setOnClickListener(this);
    }

    /**
     * 店铺列表适配器
     *
     * @param mShopList
     */
    private void setShopAdapter(List<ShopParam> mShopList) {
        mShopAdapter = new AllPowerfulAdapter<ShopParam>(R.layout.service_station_item, mShopList, new AllPowerfulAdapter.OnClickListener<ShopParam>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, ShopParam shopParam, int position) {
                //点击跳转详情页面
                Intent intent = new Intent(NearbySearchActivity.this, ShopDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_NEARBY_STORE_SEARCH);
                bundle.putString(ClientConstants.STORE_ID, shopParam.getStoreId());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder,ShopParam param) {
                super.convert(baseViewHolder, param);
                ImageView shopImg = baseViewHolder.getView(R.id.service_station_item_img);//店铺图片
                Glide.with(mContext).load(param.getStoreImageUrl()).into(shopImg);
                baseViewHolder.setText(R.id.service_station_item_title, param.getStoreName());//店铺名字
                baseViewHolder.setText(R.id.service_station_item_location, param.getStoreCity() + param.getStoreAddress());//店铺地址
                baseViewHolder.setText(R.id.service_station_item_distance, param.getDistance());//店铺距离
                LinearLayout tagLayout = baseViewHolder.getView(R.id.service_station_item_tag_layout);
                tagLayout.removeAllViews();
                for (int i = 0; i < param.getTagList().size(); i++) {
                    TextView textView = new TextView(mContext);
                    textView.setPadding(UIUtils.dip2px(10), 0, UIUtils.dip2px(10), 0);
                    textView.setBackgroundColor(Color.parseColor(param.getTagList().get(i).getTagColor()));
                    textView.setText(param.getTagList().get(i).getTagName());
                    textView.setTextSize(11);
                    textView.setGravity(Gravity.CENTER);
                    textView.setTextColor(Color.WHITE);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UIUtils.dip2px(22));
                    if (i == 0) {
                        layoutParams.setMargins(0, 0, 0, 0);
                    } else {
                        layoutParams.setMargins(UIUtils.dip2px(12), 0, 0, 0);
                    }
                    tagLayout.addView(textView, layoutParams);
                }

            }
        };
        mRecyclerView.setAdapter(mShopAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v == backBtn) {
            onBackPressed();
        } else if (v == mSearchBtn) {
            if (TextUtils.isEmpty(mSearchEdit.getText().toString())) {
                ToastUtil.showToast(this, "请输入搜索内容");
                return;
            }
            page = 1;
            mShopList.clear();
            getNearbyShops();
        }
    }

    //内容编辑框监听
    private TextWatcher onTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                page = 1;
                mShopList.clear();
                mShopAdapter.notifyDataSetChanged();
                nodataImg.setVisibility(View.GONE);
            }
        }
    };


    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getNearbyShops();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(NearbySearchActivity.this,"已经没有更多数据！！！");
            }
        }
    };


    private void getNearbyShops() {
        NetworkManager.getNearbyShopBySearchList(page, mSearchEdit.getText().toString(), lat, lng, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseShopInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.showToast(mContext, "未找到商铺");
            }
        });
    }

    private void parseShopInfoSuc(String result) {
        ToastUtil.logResult("商铺搜索",result);
        if (page == 1) {
            mShopList.clear();
        }
        NearbyShopBean bean = new Gson().fromJson(result, NearbyShopBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mShopList.addAll(bean.getData().getList());
        mShopAdapter.notifyDataSetChanged();
        nodataImg.setVisibility(View.GONE);
        if (totalPage == 0){
            nodataImg.setVisibility(View.VISIBLE);
        }else if (totalPage == 1){
            if (mShopList.size() == 0){
                nodataImg.setVisibility(View.VISIBLE);
            }
            mRefreshLayout.setEnableLoadMore(false);
        }else {
            mRefreshLayout.setEnableLoadMore(true);
        }
    }
}
